'use client';

import { createContext, useState, useEffect, useRef } from "react";

export const ThemeContext = createContext();

export const ThemeProvider = ({ children }) => {
  const [mode, setMode] = useState('dark'); // 服务端默认 dark
  const isHydrated = useRef(false); // 标记是否完成 hydration

  // 1. 客户端 hydration 完成后，从 localStorage 读取并更新主题
  useEffect(() => {
    const savedMode = localStorage.getItem('themeMode') || 'dark';
    setMode(savedMode);
    isHydrated.current = true; // 标记 hydration 完成
  }, []);

  // 2. 切换主题时同步到 localStorage
  useEffect(() => {
    if (isHydrated.current) { // 仅在 hydration 后才保存
      localStorage.setItem('themeMode', mode);
    }
  }, [mode]);

  const toggle = () => {
    setMode(prev => prev === 'dark' ? 'light' : 'dark');
  };

  return (
    <ThemeContext.Provider value={{ toggle, mode }}>
      {/* 仅在 hydration 完成后才应用主题类名，避免服务端客户端不匹配 */}
      <div className={`theme ${isHydrated.current ? mode : 'dark'}`}>
        {children}
      </div>
    </ThemeContext.Provider>
  );
};